<template>
  <div class="addGoods" :style="{minHeight:$store.state.minHeight+'rem'}">
    <myHead title="添加商品" background-color="linear-gradient(170deg,rgba(251,68,72,1) 0%,rgba(254,111,77,1) 100%)"></myHead>
    <form>
      <section>
        <div class="title">
          <div class="name">标题</div>
          <div class="txtNum">{{row['title'].length}}/30</div>
        </div>
        <div class="txt">
          <label for="">
            <input name="row[title]" id="" placeholder="例如:五一周新款 砂锅黄焖鸡+茄子香辣砂锅黄焖鸡" v-model="row['title']" />
          </label>
        </div>
        <div class="photo">
          <van-uploader v-model="row['images']" result-type="dataUrl"  multiple :after-read="afterRead"/>
<!--          <input type="file" @change="afterRead" />-->
        </div>
      </section>
      <div class="another" @click="show=true">
        <div class="name">分类</div>
        <div class="content">{{type}}</div>
        <img src="../../../static/img/yj11.png" alt="" />
      </div>
      <div class="spec">
        <div class="title">添加商品主规格</div>
        <div class="content">
          <label>
            <input type="text" placeholder="主规格名称：例如温度" v-model="skuName"></input>
          </label>
        </div>
        <div class="add" @click="add_spec()">添加</div>
      </div>
      <div class="attribute" v-if="specList" v-for="(spec,index) in specList">
        <div class="title">{{spec.name}}</div>
        <div class="content">
          <div class="name" v-if="spec.children" v-for="(attr,index) in spec.children">
            <div>{{attr.name}}</div>
            <div class="del" @click="del(index)">
              <img src="../../../static/img/business/delet.png" alt="" />
            </div>
          </div>
        </div>
        <div class="attr_add" @click="add(spec.id)">添加</div>
      </div>
      <div style="margin-top: .15rem;" v-if="skuPrice" v-for="(sku,index) in skuPrice">
        <div class="input">
          <div class="name">商品规格</div>
          <div class="content">
            <div>{{sku.goods_sku_text}}</div>
          </div>
        </div>
        <div class="specPrice">
          <div class="input">
            <div class="name">价格</div>
            <label>
              <input name="" placeholder="9.9/小杯" v-model="sku.price"></input>
            </label>
          </div>
          <div class="input">
            <div class="name">库存</div>
            <label>
              <input name="" placeholder="库存数量" v-model="sku.stock"></input>
            </label>
          </div>
        </div>
      </div>
      <div class="input margin_top">
        <div class="name">商品单位</div>
        <label>
          <input name="" placeholder="杯/盒/份/个"></input>
        </label>
      </div>
      <div class="input">
        <div class="name">商品售价</div>
        <div class="content">
          <label>
            <input name="" placeholder="商品列表显示的价格" v-model="row['price']"></input>
          </label>
        </div>
      </div>
      <div class="input">
        <div class="name">商品原价</div>
        <div class="content">
          <label>
            <input name="" placeholder="商品列表显示的原价格" v-model="row['original_price']"></input>
          </label>
        </div>
      </div>
      <div class="another" @click="showService=true">
        <div class="name">服务标签</div>
        <div class="content">{{Service}}</div>
        <img src="../../../static/img/yj11.png" alt="" />
      </div>
      <div class="input">
        <div class="name">餐盒费</div>
        <label>
          <input name="" placeholder="请填相应的餐盒费用"></input>
        </label>
      </div>
      <div class="desc">
        <div class="title">
          <div class="name">描述</div>
          <div class="txtNum">{{ descNum.length }}/300</div>
        </div>
        <div class="txt">
          <label>
            <textarea name="" placeholder="请输入商品描述" v-model="descNum"></textarea>
          </label>
        </div>
      </div>
      <div class="save" @click="submit()">保存</div >
    </form>
    <van-dialog v-model="attr" title="添加商品属性" confirmButtonColor="#FB4448" @confirm="sure_attr()" cancelButtonColor="#333333" show-cancel-button>
      <input class="dialog" v-model="attr_name" type="text" placeholder="如：常温，加热，加冰" />
    </van-dialog>
    <van-action-sheet v-model="show" :actions="actions" @select="onSelect" />
    <van-action-sheet v-model="showService" :actions="actionService" @select="onService" />
  </div>
</template>

<script>
  import Vue from 'vue';
  import myHead from "../../components/BusinessComponents/lib/myHead";
  import VDistpicker from 'v-distpicker';
  import { ActionSheet } from 'vant';
  import { Dialog } from 'vant';
  import {formatDate} from "../../methods/time";

  Vue.use(Dialog);
  Vue.use(ActionSheet);

  export default {
    name: "posting",
    data(){
      return {
        specId:1,
        attrId:1,
        is_set:0, //如果编辑商品规格传1，不改规格传0
        store_info:{},
        skuName:"",
        row:{
          "title":"", //标题
          "images":[], //商品轮播图
          "category_ids":0,//商品所属分类
          "price":"",//商品售价
          "original_price":"",//商品原价
        },
        imgUrl:[], //图片上传返回的路径
        descNum:'',
        attr:false,
        attr_name:"",
        skuPrice:[],
        specList:[],
        show: false,
        showService: false,
        actions: [], //商品分类列表
        actionService: [], //商品服务标签列表
        Service:"",
        type:"请选择商品分类",
      }
    },
    components:{
      myHead,
      VDistpicker
    },
    methods: {
      back() {
        this.$router.back()
      },
      onSelect(item) {
        // 默认情况下点击选项时不会自动收起
        // 可以通过 close-on-click-action 属性开启自动收起
        this.show = false;
        this.type = item.name;
        this.row["category_ids"] = item.id;
      },
      onService(item) {
        // 默认情况下点击选项时不会自动收起
        // 可以通过 close-on-click-action 属性开启自动收起
        this.showService = false;
        this.Service = this.Service +","+item.name;
      },
      afterRead(file){
        let src = file.file;
        console.log(src);
        let files = new FormData();
        files.append('file',src);
        this.$axios.post('http://take.zhitiaoxiaoyuan.com/api/common/upload',files,{
          headers:{
            "Content-Type":"multipart/form-data"
          }
        }).then(res=>{
          this.imgUrl.push(res.data.data.url);
          console.log(res)
        });
      },
      add:function (id) {
        this.attr = true;
        this.attrId = id;
      },
      del:function (index) {
        console.log(index);
      },
      add_spec:function(){
        if(this.skuName){
          this.specList.push({
            id:this.specId,
            name:this.skuName,
            children:[]
          });
          this.specId++;
          this.skuName='';
        }else{
          this.$myNotice("请输入内容",2000)
        }
      },
      sure_attr:function () {
        let that = this;
        //生成规格字段列表
        that.specList.forEach(function (item,index) {
          if(item.id == that.attrId){
              item.children.push({
                id:that.specId,
                name:that.attr_name
              });
              that.attr_name = "";
              that.specId++;
          }
        });
        if(that.specList.length>1){
          that.skuPriceMake();
        }else{
          //如果只有一个规格的情况下，生成skuPrice（带价格，库存的）
          that.skuPrice = [];
          that.specList[0].children.forEach(function (item,index) {
            let skuPriceId = 1;
            that.skuPrice.push({
              id:skuPriceId,
              goods_sku_ids:String(item.id),
              goods_sku_text:item.name
            });
            skuPriceId ++;
          });
        }
      },
      //重新生成skuPrice
      skuPriceMake:function(){
        let that = this;
        that.skuPrice = [];
        let array = [];
        that.specList.forEach(function (item,index) {
          let arrayChild = [];
          item.children.forEach(function (child,index_child) {
            arrayChild.push(child)
          });
          array.push(arrayChild)
        });
        let newArray = that.calcDescartes(array);
        let skuPriceId = 1;
        //根据笛卡尔积生成的数组进行拼接，生成skuPrice
        newArray.forEach(function (array,index) {
          let goods_sku_ids =[];
          let goods_sku_text =[];
          array.forEach(function (item,index) {
            goods_sku_ids.push(item.id);
            goods_sku_text.push(item.name)
          });
          let goods_sku_id;
          if(goods_sku_ids.length>1){
            goods_sku_id = goods_sku_ids.join(",")
          }else{
            goods_sku_id = String(goods_sku_ids[0]);
            console.log(goods_sku_id)
          }
          that.skuPrice.push({
            id:skuPriceId,
            goods_sku_ids:goods_sku_id,
            goods_sku_text:goods_sku_text,
            price:0,
            stock:0,
          });
          skuPriceId ++;
        });
        this.is_set = 1;
      },
      //笛卡尔积生成数组
      calcDescartes(array){
        if (array.length < 2) return array[0] || [];
        return [].reduce.call(array, function (col, set) {
          let res = [];
          col.forEach(function (c) {
            set.forEach(function (s) {
              let t = [].concat(Array.isArray(c) ? c : [c]);
              t.push(s);
              res.push(t);
            })
          });
          return res;
        });
      },
      submit:function () {
        console.log(this.imgUrl);
        if(this.row.title == ""){
          this.$myNotice("请填写商品标题",2000);
          return false
        }
        if(this.row.images.length == 0){
          this.$myNotice("请上传商品图片",2000);
          return false
        }
        if(this.row["category_ids"] == 0){
          this.$myNotice("请选择商品分类",2000);
          return false
        }
        if(this.row["price"] == ""){
          this.$myNotice("请填写商品售价",2000);
          return false
        }
        if(this.row["original_price"] == ""){
          this.$myNotice("请填写商品原价",2000);
          return false
        }
        if(this.skuPrice.length == 0){
          this.$myNotice("请填写商品规格",2000);
          return false
        }
        if(this.$route.query.id){
          var url ='/store/goods/edit_goods'
        }else{
          var url = 'store/goods/add_goods'
        }
        this.$myAxios(url, 'post', {
          "goods_id":this.$route.query.id,
          "is_set":this.is_set,
          "row[store_id]":this.store_info.id,
          "row[title]":this.row.title,
          "row[category_ids]":this.row.category_ids,
          "row[price]":this.row.price,
          "row[original_price]":this.row.original_price,
          "row[dispatch_ids]_text":"3",
          "row[image]":this.imgUrl[0],
          "row[images]":this.imgUrl,
          "sku[listData]":JSON.stringify(this.specList),
          "sku[priceData]":JSON.stringify(this.skuPrice),
          "row[status]":"down"
        }).then(res => {
          if(res.data.code == 0){
            this.$myNotice(res.data.msg,2000)
          }else{
            this.$myNotice(res.data.msg,2000);
            this.$router.push({path:"/components/BusinessComponents/goodsList/dismount"})
          }
        })
      },

    },
    mounted() {
      this.store_info = JSON.parse(localStorage.getItem("storeInfo"));
      //商品分类列表
      this.$myAxios('api/goodsCategory/category_list', 'get', {
        store_id:this.store_info.id,
      }).then(res => {
        if(res.data.code == 1){
          this.actions = res.data.data.list;
        }else{
          this.$myNotice(res.data.msg,2000)
        }
      });
      //商品服务标签列表
      this.$myAxios('api/goods/goods_service', 'get', {
        store_id:this.store_info.id,
      }).then(res => {
        if(res.data.code == 1){
          this.actionService = res.data.data.list;
        }else{
          this.$myNotice(res.data.msg,2000)
        }
      });
      // 获取商品详情
      if(this.$route.query.id){
        console.log(this.$route.query.id);
        this.$myAxios('/store/goods/goods_info', 'get', {
          goods_id:this.$route.query.id
        }).then(res => {
          if(res.data.code == 1){
            this.row = res.data.data.row;
            this.skuPrice = res.data.data.skuPrice;
            if(this.actions){
              for(let i=0;i<this.actions.length;i++){
                if(this.row.category_ids == this.actions[i].id){
                  this.type = this.actions[i].name
                }
              }
            }
          }else{
            this.$myNotice(res.data.msg,2000)
          }
        });
      }
    },
    watch:{
      txtNum(){
        this.txtNum.length>=30?this.txtNum = this.txtNum.substring(0,30):'';
      },
      descNum(){
        this.descNum.length>=300?this.descNum = this.descNum.substring(0,300):'';
      }
    }
  }
</script>

<style scoped>
  .addGoods{
    background: #F5F5F5;
    padding-bottom: .1rem;
  }
  .addGoods input{
    border: none;
    width: 100%;
  }
  .addGoods input::placeholder{
    color: #A5A5A5;
  }

  .addGoods header {
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 88;
    flex-flow: row;
    box-sizing: border-box;
  }
  .addGoods header .top{
    height: .5rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(170deg,rgba(251,68,72,1) 0%,rgba(254,111,77,1) 100%);
    padding: 0 .1rem;
  }
  .addGoods header > div > img {
    width: .11rem;
    height: .18rem;
  }

  .addGoods header > div > span {
    font-size: .18rem;
    font-weight: 500;
    color: #ffffff;
  }
  .addGoods header .add{
    font-size: .16rem;
    font-weight: normal;
  }
  .addGoods section {
    width: 100%;
    background-color: #ffffff;
    box-sizing: border-box;
    padding: .6rem .16rem 0;
    margin-bottom: .1rem;
  }
  .addGoods .title{
    display: flex;
    justify-content: space-between;
  }
  .addGoods .name{
    font-size: .15rem;
    color: #333333;
  }
  .addGoods .txt input{
    width: 100%;
    border: none;
    padding: .12rem .02rem .24rem;
    font-size: .14rem;
  }
  .addGoods .txt input::placeholder{
    color: #A5A5A5;
  }
  .addGoods .txtNum{
    color: #A5A5A5;
  }
  .addGoods .desc{
    background: #ffffff;
    padding: .13rem;
    margin-top: .1rem;
  }
  .addGoods .desc textarea{
    width: calc(100% - .1rem);
    height: .6rem;
    padding: .15rem .05rem;
    border:none;
    font-size: .14rem;
  }
  .addGoods .spec{
    margin-top: .08rem;
    display: flex;
    background-color: #ffffff;
    align-items: center;
    font-size: .15rem;
    padding: 0.12rem .17rem;
  }
  .addGoods .spec .content{
    margin-left: .1rem;
  }
  .addGoods .spec .add{
    color: #FFBA20;
  }
  .addGoods .attribute{
    display: flex;
    background-color: #ffffff;
    align-items: center;
    justify-content: space-between;
    font-size: .15rem;
    padding: .12rem .17rem;
    border-top: 1px solid #EBEBEB;
  }
  .addGoods .attribute .attr_add{
    color: #F0A706;
  }
  .addGoods .attribute .content{
    display: flex;
  }
  .addGoods .attribute .content .name{
    position: relative;
  }
  .addGoods .attribute .content .name>div:nth-child(1){
    background: #FEC2C4;
    border: 1px solid #FF2227;
    padding: .02rem .04rem;
    margin-left: .12rem;
    font-size: .12rem;
    border-radius: .04rem;
    color: #FD2F33;
  }
  .addGoods .attribute .content .name>div:nth-child(2){
    width: .14rem;
    height: .14rem;
    position: absolute;
    right: -.07rem;
    top: -.07rem;
  }
  .addGoods .spec .specList .title{
    padding-right: .1rem;
  }
  .addGoods .specPrice{
    margin-top: .05rem;
  }
  .addGoods .another{
    display: flex;
    justify-content: space-between;
    background: #ffffff;
    margin: .11rem 0 0;
    height: .48rem;
    align-items: center;
    padding: 0 .17rem;
  }
  .addGoods .another .name{
    width: .6rem;
    margin-right: .17rem;
  }
  .addGoods .add img{
    width: .15rem;
    height: .15rem;
    margin-right: .1rem;
  }

  .addGoods .content{
    flex-grow: 1;
    font-size: .14rem;
    color: #A5A5A5;
  }
  .addGoods .another img{
    width: .06rem;
  }
  .addGoods .input{
    border-top: 1px solid #EBEBEB;
    display: flex;
    background: #ffffff;
    padding: 0 .17rem;
    justify-content: space-between;
    align-items: center;
    height: .48rem;
  }
  .addGoods .input .name{
    width: .6rem;
    margin-right: .17rem;
  }
  .addGoods .input label{
    flex-grow: 1;
  }
  .addGoods .input label input{
    width: 100%;
    border:none;
    font-size: .14rem;
  }
  .addGoods .save{
    width: 3.4rem;
    height: .48rem;
    background: linear-gradient(170deg,rgba(251,68,72,1) 0%,rgba(254,111,77,1) 100%);
    border-radius: .24rem;
    line-height: 0.48rem;
    text-align: center;
    margin: .22rem auto 0;
    font-size: .15rem;
    color: #ffffff;
  }
  >>>.van-dialog__header{
    line-height:.24rem;
    padding-top:.24rem;
  }
  >>>.van-dialog__content{
    margin: .16rem .12rem .23rem;
  }
  >>>.van-dialog{
    width: 3.2rem;
    font-size: .16rem;
    border-radius:.16rem;
  }
  >>>.van-button{
    font-size: .16rem;
    height: .5rem;
    line-height: .48rem;
  }
  .addGoods .dialog{
    width: calc(100% - 0.18rem);
    height: .36rem;
    border: none;
    background: #F6F6F6;
    border-radius: .08rem;
    padding: 0 .09rem;
    font-size: .14rem;
  }
  .addGoods .margin_top{
    margin-top: .12rem;
  }
</style>

